<template>
  <div class="ImgUpload">
    <n-upload
        :multiple="false"
        list-type="image-card"
        :headers="{token}"
        :action="action"
        :disabled="props.disabled"
        :max="1"
        @before-upload="beforeUpload"
        :on-finish="handleChange"
        :on-remove="handleRemove"
        v-model:file-list="fileList"
    >
    </n-upload>
  </div>
</template>

<script lang="ts">
export default {
  name: "ImgUpload"
}
</script>

<script setup lang="ts">
import {onMounted, ref, watch} from "vue"
import {UploadFileInfo} from 'naive-ui'
import url from '@/static/config'
import useMsg from '@/hooks/useMsg'
import {ums_imgdel} from '@/api/ums'
import {sms_product_del} from '@/api/sms'
const { error, success } = useMsg()
const token: string = sessionStorage.getItem('token')!

const emit = defineEmits<{
  (e: 'update:value', value: string): void
  (e: 'change', value: string): void
}>()

const props = defineProps<{
  value: any,
  disabled: boolean,
  url?: string | boolean
}>()

const action = url + (props.url || 'ums/imgUpload')

const fileList = ref<UploadFileInfo[]>(
    props.value ? props.value.split(',').map((item, i) => ({
      id: 'url-test' + i,
      name: 'URL 测试',
      url: url + (props.url? "static/product/" : "static/images/" ) + props.value as string,
      status: 'finished'
    })) : []
)

watch(() => props.value, (n,v) => {
  if (n) {
    fileList.value = n.split(',').map((item, i) => ({
      id: 'url-test' + i,
      name: 'URL 测试',
      url: url + (props.url? "static/product/" : "static/images/" ) + n as string,
      status: 'finished'
    }))
  }
})

const handleChange = (options:{ file: UploadFileInfo, event?: ProgressEvent }) => {
  const res = JSON.parse(options.event?.target?.response as string)
  if (res.code === '200'){
    success(res.message)
    emit('update:value', res.data as string)
    emit('change', res.data as string)
  }
}


function beforeUpload (data: {
  file: UploadFileInfo
  fileList: UploadFileInfo[]
}) {
  /*if (data.file.file?.type !== 'image/png' && data.file.file?.type !== 'image/jpeg') {
    error('只能上传png,jpg,jpeg格式的图片文件，请重新上传')
    return false
  }*/
  return true
}

function handleRemove (options: { file: UploadFileInfo, fileList: Array<UploadFileInfo> }): Promise<boolean> | boolean |any{
  const urls = options.file.url!.split("/")
  const url = urls[urls.length - 1]
  if (props.url){
    sms_product_del({url}).then(res => {
      emit('update:value', "")
      emit('change', "")
    }, err => {
      emit('update:value', "")
      emit('change', "")
    })
  }else {
    ums_imgdel({url}).then(res => {
      emit('update:value', "")
      emit('change', "")
    }, err => {
      emit('update:value', "")
      emit('change', "")
    })
  }
}

onMounted( () => {
} )
</script>

<style scoped lang="scss">

</style>
